#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <chrono>
#include <functional>
class ThreadPool {
private:
    std::vector<std::thread> workers;
    std::queue<std::function<void()>> tasks;
    std::mutex queue_mutex;
    std::condition_variable condition;
    std::atomic<bool> stop;
    std::atomic<int> idleThreads;
    int minThreads, maxThreads;

    void worker() {
        while (!stop) {
            std::function<void()> task;
            {
                std::unique_lock<std::mutex> lock(this->queue_mutex);
                this->condition.wait(lock, [this] {
                    return this->stop || !this->tasks.empty();
                });
                if (this->stop && this->tasks.empty())
                    return;
                task = std::move(this->tasks.front());
                this->tasks.pop();
            }

            idleThreads--;
            task();
            idleThreads++;
            adjustThreadPool();
        }
    }

    void adjustThreadPool() {
        std::lock_guard<std::mutex> lock(queue_mutex);
        int currentThreadCount = workers.size();
        if (tasks.size() > workers.size() && workers.size() < maxThreads) {
            workers.emplace_back(&ThreadPool::worker, this);
            idleThreads++;
            std::cout << "Increased thread count to " << workers.size() << std::endl;
        }
        else if (idleThreads > minThreads && tasks.empty()) {
            stop = true;
            condition.notify_one();
            std::cout << "Reduced thread count to " << workers.size() - 1 << std::endl;
        }
    }

public:
    ThreadPool(int min = 2, int max = 4) : minThreads(min), maxThreads(max), stop(false) {
        idleThreads = min;
        for (int i = 0; i < minThreads; ++i)
            workers.emplace_back(&ThreadPool::worker, this);
        std::cout << "Initial thread count: " << workers.size() << std::endl;
    }

    ~ThreadPool() {
        stop = true;
        condition.notify_all();
        for (std::thread &worker : workers)
            worker.join();
        std::cout << "Final thread count: " << workers.size() << std::endl;
    }

    template<class F>
    void enqueue(F&& f) {
        {
            std::unique_lock<std::mutex> lock(queue_mutex);
            if (stop)
                throw std::runtime_error("enqueue on stopped ThreadPool");
            tasks.emplace(std::forward<F>(f));
        }
        condition.notify_one();
    }
};

int main() {
    ThreadPool pool(2, 4);

    for (int i = 0; i < 10; ++i) {
        pool.enqueue([i]() {
            std::cout << "Executing task " << i << std::endl;
            std::this_thread::sleep_for(std::chrono::seconds(1));
        });
    }

    std::this_thread::sleep_for(std::chrono::seconds(12));  // Wait for all tasks to complete

    return 0;
}